//
//  NWUserAccountViewModel.swift
//  Weibo
//
//  Created by Northwan on 16/1/23.
//  Copyright © 2016年 Northwan. All rights reserved.
//

import UIKit

class NWUserAccountViewModel {
    
    static let sharedAccount:NWUserAccountViewModel = NWUserAccountViewModel()
    
    var userAccount:NWUserAccount?
    
    //判断是否登录
    var userLogon:Bool{
        return accessToken != nil
    }
    
    //getOnly
    var accessToken: String?{
        if let accessToken = userAccount?.access_token where !isExpires{
            //判断是否过期
            return accessToken
        }
        return nil
    }
    
    var isExpires: Bool{
        guard let expiresDate = userAccount?.expiresDate else{
            return true
        }
        //与当前时间进行对比，判断是否过期
        if NSDate().compare(expiresDate) == NSComparisonResult.OrderedAscending {//OrderedAscending 是升序，从小到大
            return false
        }
        return true
    }
    
    private init() {
        // 从沙盒里面解档
        userAccount = NSKeyedUnarchiver.unarchiveObjectWithFile(accountPath) as? NWUserAccount
        printLog(self.accountPath)
        if isExpires {
            userAccount = nil
        }
    }
    
    // 用户信息保存的位置
    private var accountPath:String {
        return (NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).last! as NSString).stringByAppendingPathExtension("useraccount.archive")!
    }
}


//MARK: - 网络请求
extension NWUserAccountViewModel{
    /**
     获取accessToken
     
     - parameter code: 授权码
     */
    func loadAccessToken(code:String,finished:(isSuccessed:Bool) -> Void){
        NWNetworkTools.shareTools.loadAccessToken(code) { (response, error) -> Void in
            if error != nil{
                printLog("请求失败\(error)")
                finished(isSuccessed: false)
                return
            }
            printLog("请求成功\(response)")
            
            //判断是否是一个字典：'?'与'!'强行解包的时候用哪个,就看前面是否是一个可选值
            guard let dict = response as? [String: AnyObject] else{
                return
            }
            let account = NWUserAccount(dict: dict)
            //获取用户信息
            self.loadUserInfo(account,finished: finished)
        }
    }
    
    /**
     获取用户信息
     
     - parameter userAccount: 用户信息model
     */
    func loadUserInfo(userAccount: NWUserAccount,finished:(isSuccessed:Bool) -> Void){
        NWNetworkTools.shareTools.loadUserInfo(userAccount) { (response, error) -> Void in
            if error != nil{
                printLog(error)
                finished(isSuccessed: false)
                return
            }
            guard let resDic = response as? [String: AnyObject] else{
                printLog("返回的不是一个字典")
                return
            }
            userAccount.avatar_large = resDic["avatar_large"] as? String
            userAccount.screen_name = resDic["screen_name"] as? String
            printLog(userAccount)
            self.userAccount = userAccount
           
            // 保存对象 － 会调用对象的 encodeWithCoder 方法
            NSKeyedArchiver.archiveRootObject(userAccount, toFile: self.accountPath)
            printLog(self.accountPath)
            finished(isSuccessed: true)
        }
    }
}
